<template>
  <div>
    <!--面包屑-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
        <el-button type="primary" @click="addRoleVisible=true" class="jun">添加角色</el-button>


      <!--表格数据-->
      <el-table
        :data="tableDate"
        border
        stripe
        style="width: 100%">
        <el-table-column type="expand">
          <template v-slot="roleChildren">
            <!--先渲染一级菜单-->
            <el-row :class="['b_bottom' , i === 0 ? 'b_top' : '' , 'vcenter']" v-for="(item_1 , i) in roleChildren.row.children" :key="item_1.id">
              <el-col :span="5">
                <el-tag type="primary">{{item_1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="19">
                <!--先渲染二级菜单-->
                <el-row :class="[i2 === 0 ? '' : 'b_top' , 'vcenter']" v-for="(item_2 , i2) in item_1.children" :key="item_2.id">
                  <el-rol :span="6">
                    <el-tag type="success">{{item_2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-rol>
                  <!--先渲染三级菜单-->
                  <el-rol :span="18">
                    <el-tag type="warning" closable v-for="item_3 in item_2.children" :key="item_3.id">{{item_3.authName}}</el-tag>
                  </el-rol>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column
          label="#"
          type="index">
        </el-table-column>
        <el-table-column
          prop="roleName"
          label="角色名称">
        </el-table-column>
        <el-table-column
          prop="roleDesc"
          label="角色描述">
        </el-table-column>
        <el-table-column
          label="操作">
          <template v-slot="mySlot">
            <el-button @click="editDialog(mySlot.row.id)" type="primary" icon="el-icon-edit">编辑</el-button>
            <el-button @click="delDialog(mySlot.row)"  type="danger" icon="el-icon-delete">删除</el-button>
            <el-button @click="treeDialog(mySlot.row)" type="warning" icon="el-icon-setting">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!--添加用户的弹出框-->
    <el-dialog title="添加用户" v-model="addRoleVisible" width="50%">
      <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" class="demo-ruleForm" label-width="80px">
        <el-form-item label="用户名称" prop="roleName">
          <el-input v-model="ruleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="ruleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="resetForm('ruleForm')">取 消</el-button>
          <el-button type="primary" @click="addRole('ruleForm')">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!--删除用户的弹出框-->
    <el-dialog
      title="提示"
      v-model="delDialogVisible"
      width="50%"
      center>
      <span>您确定要删除 {{roleName}} 用户名称吗？</span>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="delDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="del">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!--编辑用户的弹出框-->
    <el-dialog
      title="编辑用户信息"
      v-model="editDialogVisible"
      width="50%"
      center>

      <el-form :model="updateForm" status-icon :rules="rules" ref="update  Form" class="demo-ruleForm" label-width="70px">
        <el-form-item label="角色ID" prop="id">
          <el-input v-model="updateForm.id" readonly disabled></el-input>
        </el-form-item>
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="updateForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="updateForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="edit">确 定</el-button>
        </span>
      </template>
    </el-dialog>

      <!--分配权限的弹出框-->
      <el-dialog
        title="分配权限"
         v-model="showTreeDialog"
        width="30%"
        :before-close="handleClose">

      <!--树-->
      <el-tree
      :data="rolesList"
      :props="treeProps"
      show-checkbox
      node-key="id"
      :default-checked-keys="checkArr"
      default-expand-all
      ref="treeRef">
      </el-tree>

        <template #footer>
          <span class="dialog-footer">
            <el-button @click="showTreeDialog = false">取 消</el-button>
            <el-button type="primary" @click="setRoleInfo">确 定</el-button>
          </span>
        </template>
      </el-dialog>

      <!--添加用户的弹出框-->
<!--      <el-dialog title="添加角色" v-model="addUserVisible" width="50%">-->
<!--        <el-form :model="roleForm" status-icon :rules="rules" ref="ruleForm" class="demo-ruleForm" label-width="70px">-->
<!--          <el-form-item label="用户名" prop="username">-->
<!--            <el-input v-model="ruleForm.username"></el-input>-->
<!--          </el-form-item>-->
<!--          <el-form-item label="密码" prop="password">-->
<!--            <el-input v-model="ruleForm.password"></el-input>-->
<!--          </el-form-item>-->
<!--          <el-form-item label="邮箱" prop="email">-->
<!--            <el-input v-model="ruleForm.email"></el-input>-->
<!--          </el-form-item>-->
<!--          <el-form-item label="手机" prop="mobile">-->
<!--            <el-input v-model="ruleForm.mobile"></el-input>-->
<!--          </el-form-item>-->
<!--        </el-form>-->
<!--        <template #footer>-->
<!--        <span class="dialog-footer">-->
<!--          <el-button @click="resetForm('ruleForm')">取 消</el-button>-->
<!--          <el-button type="primary" @click="addUser('ruleForm')">确 定</el-button>-->
<!--        </span>-->
<!--        </template>-->
<!--      </el-dialog>-->


  </div>
</template>

<script>
import {ElMessage} from "element-plus";

export default {
  name: "roles",
  data(){
    return {
      addRoleDialog : false,
      showTreeDialog : false,
      addRoleVisible: false,
      delDialogVisible: false,
      editDialogVisible: false,
      ruleForm: {
        roleName: '',
        roleDesc: '',
      },
      updateForm: {

      },
      tableDate: [],
      rolesList: [],
      checkArr: [],
      rules: {
        roleName: [
          { required: true, message: '请输入用户名称', trigger: 'blur'}
        ],
        roleDesc: [
          { required: true, message: '请输入用户描述', trigger: 'blur'}
        ]
      },
      role_id: 0,
      treeProps: {
        label: 'authName',      //规定，到时候，rolesList里面的authName这个字段，作为树节点的内容
        children: 'children'
      },
      roleId: 0,
      roleName:''
    }
  },
  created() {
    this.getAllRoles();
  },
  methods: {
    //获取所有角色数据
    getAllRoles(){
      this.axios.get('roles').then(resp=>{
        console.log(resp);
        if( resp.data.meta.status !== 200) return ElMessage.error('获取角色列表错误');
        this.tableDate = resp.data.data;
      }).catch(err=>{
        console.log(err);
      })
    },
    //添加角色
    addRole(formName){
      this.axios.post('roles',this.ruleForm).then(data=>{
        console.log(data);
        if( data.data.meta.status !== 201 ) return ElMessage.error('添加失败');

        ElMessage.success('添加成功');
        this.resetForm(formName);
        this.getAllRoles();    //重新获取数据，实时刷新
      }).catch(err=>{
        console.log(err);
      });
    },
    editDialog(id){
      this.editDialogVisible = true;
      this.roleId = id;

      this.axios.get(`roles/${this.roleId}`).then(resp=>{
        this.updateForm = resp.data.data
      }).catch(err=>{
        console.log(err)
      })
    },
    edit(){
      //修改用户数据
      this.axios.put(`roles/${this.roleId}`,{
        roleName: this.updateForm.roleName,
        roleDesc: this.updateForm.roleDesc
      }).then(resp=>{
        if( resp.data.meta.status !== 200 ) return ElMessage.error('修改失败')

        ElMessage.success('修改成功');
        this.editDialogVisible = false;
        this.getAllRoles();
      }).catch(err=>{
        console.log(err)
      })
    },
    delDialog(row){
      this.roleId = row.id;
      this.roleName = row.roleName;

      this.delDialogVisible = true;
    },
    del(){
      this.axios.delete(`roles/${this.roleId}`).then(resp=>{
        if( resp.data.meta.status !== 200 ) return ElMessage.error('删除失败')

        ElMessage.success('删除成功');
        this.delDialogVisible = false;
        this.getAllRoles();
      }).catch(err=>{
        console.log(err);
      })
    },
    //显示权限列表弹框
    treeDialog(row){
      this.role_id = row.id;
      //开始发送请求
      this.axios.get('rights/tree').then(resp=>{
        console.log( resp );
        if( resp.data.meta.status !== 200 ) return ElMessage.error('获取角色列表');
        this.rolesList = resp.data.data;
      }).catch(err=>{
        console.log(err);
      })
      //接着，得到我的选中的这个节点的权限
      this.getNodeById(row);
      this.showTreeDialog = true;
    },
    getNodeById(node){
      //如果没有字节点，那就是三级节点，那么，我们要的，就是这个ID
      if( !node.children ){
        return this.checkArr.push(node.id);
      }
      //有节点，开始循环，去所有的子节点
      node.children.forEach(item=>{
        this.getNodeById(item);
      })
    },
    //关闭表单所做的事情
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.addRoleVisible = false;
    },
    //设置分配权限
    setRoleInfo(){
      //先得到所有的选中的节点的ID，以及，半选中的节点的ID
      let keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ];
      let keyStr = keys.join(',');
      console.log( keyStr );
      this.axios.post(`roles/${this.role_id}/rights`,{
        rids: keyStr
      }).then(resp=>{
        if( resp.data.meta.status !== 200 ) return ElMessage.error('授权失败');
        ElMessage.success('更新成功');
        this.showTreeDialog = false;
        this.getAllRoles();
      }).catch(err=>{
        console.log(err);
      });
    },
    handleClose(){
      //清空数据
      this.checkArr = [];
      this.showTreeDialog = false;
    }

  }
}
</script>

<style scoped>
.el-breadcrumb{
  font-size: 20px;
}
.box-card, .el-pagination{
  margin-top: 20px;
}

.el-tag{
  margin: 10px;
}
.b_bottom{
  border-bottom: 1px solid #eee;
}
/*上边框的样式*/
.b_top{
  border-top: 1px solid #eee;
}
/*垂直居中*/
.vcenter{
  display: flex;
  align-items: center;
}
.jun{
  margin-bottom: 20px;
}
</style>
